﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using umbraco.BasePages;
using umbraco.cms.businesslogic.member;
using umbraco.DataLayer;



namespace Designit.Umb.Newsletter.Custom.plugins.designit.newsletter
{
    public partial class createNewsletterCampaign : UmbracoEnsuredPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                iframe1.Attributes.Add("onload", "setData();");
                iframePreview.Attributes.Add("onload", "resizeIframe('iframePreview');");
                NextButton.OnClientClick = @"loadData();";



                //Panel 1
                Session["step"] = 1;
                ProgressLiteral.Text = "New campaign - step 1/4";
                Repeater1.DataSource = MemberGroup.GetAll;
                Repeater1.DataBind();

                for (int i = 0; i < Repeater1.Items.Count; i++)
                {

                    Literal lt = (Literal)Repeater1.Items[i].FindControl("LiteralRecipents");

                    if (lt != null)
                    {
                        lt.Text = "(" + MemberGroup.GetByName(lt.Text).GetMembers().Count() + " recipients)";
                    }

                    lt = (Literal)Repeater1.Items[i].FindControl("LiteralName");
                    if (lt.Text == "Bounced")
                    {
                        Repeater1.Items[i].Visible = false;
                    }
                }

                //Panel 2
                if (Request["title"] != null)
                {
                    txtCampaignName.Text = Request["title"];
                }
                var doc = new XmlDocument();
                var path = @"/config/designit/newsletter/mailSettings.config";
                path = Server.MapPath(path);
                doc.Load(path);
                var xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Name']");
                txtFrom.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Mail']");
                TxtReply.Text = xnode.Attributes[1].Value;
                
                using (var reader =
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select alias from newsLetterTemplate"))
                {
                    while (reader.Read())
                    {
                        ListBox1.Items.Add(reader.GetString("alias"));

                    }
                }
                checkLinkGoogle.Enabled = false;


                //check if we are in edit state
                if (Session["campaignId"] != null)
                {
                    string pageId = Session["campaignId"].ToString();
                    if (pageId.Length > 0)
                    {
                        Edit(pageId);
                    }

                }


            }


        }

        protected void checkLinkTrack_CheckedChanged(object sender, EventArgs e)
        {
            if (checkLinkTrack.Checked)
            {
                checkLinkGoogle.Enabled = true;
            }
            else
            {
                checkLinkGoogle.Enabled = false;
            }

        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //add buttons to umbraco pane

            ImageButton save = UmbracoPanel1.Menu.NewImageButton();
            save.ImageUrl = umbraco.GlobalSettings.Path + "/images/editor/save.gif";
            save.Click += new ImageClickEventHandler(SaveDraftButton_Click);
            save.OnClientClick = @"loadData();";
            save.Attributes.Add("Title", "Save");

            ImageButton testMail = UmbracoPanel1.Menu.NewImageButton();
            testMail.ID = "btnTest";
            testMail.Visible = false;
            testMail.ImageUrl = umbraco.GlobalSettings.Path + "/images/designit/newsletter/save_test.gif";
            testMail.Click += new ImageClickEventHandler(TestMailButton_Click);
            testMail.Attributes.Add("Title", "Send test mail");

            ImageButton sendMail = UmbracoPanel1.Menu.NewImageButton();
            sendMail.ID = "btnSend";
            sendMail.Visible = false;
            sendMail.ImageUrl = umbraco.GlobalSettings.Path + "/images/designit/newsletter/save_send.gif";
            sendMail.Click += new ImageClickEventHandler(SendCampaignButton_Click);
            sendMail.Attributes.Add("Title", "Send campaign");

        }

        private void Edit(string id)
        {
            using (var reader =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsletterCampaignNewsletter where id=@id",
                                                                          umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", Int32.Parse(id))))
            {

                while (reader.Read())
                {
                    txtCampaignName.Text = reader.GetString("camptitle");
                    txtSubjct.Text = reader.GetString("campsubject");
                    txtFrom.Text = reader.GetString("campfrom");
                    TxtReply.Text = reader.GetString("campreplyMail");
                    contentTextbox.Text = reader.GetString("campcontent");

                    if (reader.GetString("campTrack") == "true")
                    {
                        checkLinkTrack.Checked = true;
                        checkLinkGoogle.Enabled = true;
                    }

                    if (reader.GetString("campGoogle") == "true")
                    {
                        checkLinkGoogle.Checked = true;
                    }

                    string template = reader.GetString("campTemplate");
                    if (template.Length > 0)
                    {
                        ListBox1.SelectedValue = template;
                    }
                }
            }

            //check if grps are assigned to campaign
            using (var reader =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsletterCampaign2Group where campaignId=@id",
                                                                          umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id)))
            {
                while (reader.Read())
                {


                    for (int i = 0; i < Repeater1.Items.Count; i++)
                    {

                        Literal lt = (Literal) Repeater1.Items[i].FindControl("LiteralName");

                        if (lt.Text == reader.GetString("groupName"))
                        {
                            CheckBox cb = (CheckBox) Repeater1.Items[i].FindControl("CheckboxGroup");
                            cb.Checked = true;

                        }


                    }
                }
            }
        }

        protected void NextButton_Click(object sender, EventArgs e)
        {

            if ((int)Session["step"] == 1)
            {
                pp_step2.Visible = true;
                pp_step1.Visible = false;
                BackButton.Enabled = true;

                Session["step"] = 2;
                ProgressLiteral.Text = "New campaign - step 2/4";
            }
            else if ((int)Session["step"] == 2 && ListBox1.SelectedIndex > -1)
            {
                pp_step2.Visible = false;
                pp_step3.Visible = true;
                Session["step"] = 3;
                ProgressLiteral.Text = "New campaign - step 3/4";

                iframe1.Attributes.Add("src", "/base/embedNewsletter/Emb/" + ListBox1.SelectedItem.Value + ".aspx");

            }
            else if ((int)Session["step"] == 3)
            {
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("update newsLetterCampaignTempContent set tempContent=@Content where id=1",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content", contentTextbox.Text));
                pp_step3.Visible = false;
                pp_step4.Visible = true;
                NextButton.Enabled = false;
                Session["step"] = 4;
                UmbracoPanel1.Menu.FindControl("btnTest").Visible = true;
                UmbracoPanel1.Menu.FindControl("btnSend").Visible = true;
                ProgressLiteral.Text = "New campaign - step 4/4";
                iframePreview.Attributes.Add("src", "/base/embedNewsletter/Embstep4/" + ListBox1.SelectedItem.Value + ".aspx");

            }
        }

        protected void BackButton_Click(object sender, EventArgs e)
        {
            if ((int)Session["step"] == 2)
            {
                pp_step1.Visible = true;
                pp_step2.Visible = false;
                BackButton.Enabled = false;
                Session["step"] = 1;
                ProgressLiteral.Text = "New campaign - step 1/4";
            }
            else if ((int)Session["step"] == 3)
            {
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("update newsLetterCampaignTempContent set tempContent=@Content where id=1",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content", contentTextbox.Text));
                pp_step2.Visible = true;
                pp_step3.Visible = false;
                Session["step"] = 2;
                ProgressLiteral.Text = "New campaign - step 2/4";
            }
            else
            {
                pp_step3.Visible = true;
                pp_step4.Visible = false;
                NextButton.Enabled = true;
                Session["step"] = 3;
                UmbracoPanel1.Menu.FindControl("btnTest").Visible = false;
                UmbracoPanel1.Menu.FindControl("btnSend").Visible = false;
                ProgressLiteral.Text = "New campaign - step 3/4";

            }
        }

        protected void SaveDraftButton_Click(object sender, EventArgs e)
        {
            SaveCampaign();
            Response.Redirect("editNewsletterCampaign.aspx?id=1");
        }

        protected void TestMailButton_Click(object sender, EventArgs e)
        {
            int campaignId = SaveCampaign();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(@"<script type=""text/javascript"">");
            sb.AppendLine("top.openModal('plugins/designit/newsletter/testMail.aspx?id=" + campaignId + "', 'Send test mail', 200,500);");
            sb.AppendLine("</script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "testPopUp", sb.ToString());

        }

        protected void SendCampaignButton_Click(object sender, EventArgs e)
        {
            int campaignId = SaveCampaign();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(@"<script type=""text/javascript"">");
            sb.AppendLine("top.openModal('plugins/designit/newsletter/DelaySend.aspx?id=" + campaignId + "', 'Send delayed mail', 276,608);");
            sb.AppendLine("</script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "popUp", sb.ToString());

        }

        private int SaveCampaign()
        {
            string selectedTemplate;
            string contentText = "";
            string templateText = "";
            if (ListBox1.SelectedIndex > -1)
            {
                selectedTemplate = ListBox1.SelectedItem.ToString();
                contentText = contentTextbox.Text;
                var path = Bll.Helper.GetTemplateDir();
                path = Path.Combine(path, string.Format("{0}.master", ListBox1.SelectedValue));

                if (File.Exists(path))
                {
                    templateText = File.ReadAllText(path);
                }
            }
            else
            {
                selectedTemplate = "";
            }

            string track;
            if (checkLinkTrack.Checked)
            {
                track = "true";

            }
            else
            {
                track = "false";
            }

            string googleTrack;
            if (checkLinkGoogle.Checked)
            {
                googleTrack = "true";

            }
            else
            {
                googleTrack = "false";
            }

            if (Session["campaignId"] == null)
            {
                Session["campaignId"] = "";
            }

            if (Session["campaignId"].ToString().Length > 0)
            {
                int id = Int32.Parse(Session["campaignId"].ToString());
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery(
                    "update newsletterCampaignNewsletter set camptitle=@title, campsubject=@subject, campstatus=@status, campfrom=@from, campreplyMail=@replyMail, campTemplate=@Template, campContent=@Content, campTemplatecontent=@campTemplatecontent, campTrack=@track, campGoogle=@google where id=@id",
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@title", txtCampaignName.Text),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@subject", txtSubjct.Text),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@status", "draft"),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@from", txtFrom.Text),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@replyMail", TxtReply.Text),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Template", selectedTemplate),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content", contentText),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campTemplatecontent", templateText),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@track", track),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@google", googleTrack),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id));
                SignGroupToCampaign(id);
                SignMemberToCampaign(id);
                return id;
            }
            else
            {
                int id = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>("insert into newsletterCampaignNewsletter(camptitle, campsubject, campstatus, campfrom, campreplyMail, campTemplate, campContent, campTemplatecontent, campTrack, campGoogle) values(@title, @subject, @status, @from, @replyMail, @Template, @Content, @campTemplatecontent, @track, @google);select @@Identity",
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@title", txtCampaignName.Text),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@subject", txtSubjct.Text),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@status", "draft"),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@from", txtFrom.Text),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@replyMail", TxtReply.Text),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Template", selectedTemplate),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content", contentText),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campTemplatecontent", templateText),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@track", track),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@google", googleTrack));
                SignGroupToCampaign(id);
                SignMemberToCampaign(id);
                return id;
            }

        }

        private void SignMemberToCampaign(int id)
        {
            umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsletterCampaign2Member where campaignId=@id",
                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id));
            for (int i = 0; i < Repeater1.Items.Count; i++)
            {

                CheckBox checkBox = (CheckBox)Repeater1.Items[i].FindControl("CheckboxGroup");

                if (checkBox.Checked)
                {
                    Literal lt = (Literal)Repeater1.Items[i].FindControl("LiteralName");

                    if (lt != null)
                    {
                        MemberGroup memberGroup = MemberGroup.GetByName(lt.Text);
                        List<int> memberIds = new List<int>();

                        //read  all membeId's into a list
                        foreach (var member in memberGroup.GetMembers())
                        {
                            memberIds.Add(member.Id);
                        }

                        //check if member is allready assigned to the campaign
                        using (var reader =
                            umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsLetterCampaign2Member where campaignId=@campaignId",
                                                                                      umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", id)))
                        {
                            while (reader.Read())
                            {
                                if (memberGroup.HasMember(reader.GetInt("memberId")))
                                {
                                    memberIds.Remove(reader.GetInt("memberId"));
                                }
                            }
                        }

                        //add nonassigned members to the campaign
                        foreach (var memberId in memberIds)
                        {
                            umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery(
                                "insert into newsLetterCampaign2Member (campaignId, memberId) values(@campaignId, @memberId)",
                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", id),
                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@memberId", memberId));
                        }

                    }
                }
            }
        }

        private void SignGroupToCampaign(int id)
        {
            umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsletterCampaign2Group where campaignId=@id",
                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id));
            for (int i = 0; i < Repeater1.Items.Count; i++)
            {

                CheckBox cb = (CheckBox)Repeater1.Items[i].FindControl("CheckboxGroup");

                if (cb.Checked)
                {
                    Literal lt = (Literal)Repeater1.Items[i].FindControl("LiteralName");
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("Insert into newsLetterCampaign2Group(campaignId, groupName, groupId) values(@id, @name, @groupId)",
                                                                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id),
                                                                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@name", lt.Text),
                                                                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("groupId", MemberGroup.GetByName(lt.Text).Id));


                }


            }
        }

    }
}